﻿using System;
using System.Web.UI.WebControls;
using Telerik.Web.UI;
using System.Collections.ObjectModel;
using Core.Message;
using Core.NTier.UserInterface;
using Core.ExceptionHandling;
using Core.Cache;
using System.Web.Security;
using Core.Security.CoreMembership;
using Core.Security.Business;
using Core.Common.Session;
using System.Web;
using Core.Controls.Message;
using Core.Message.Entities;
using Core.Configs;
using vHCS.SYS.Business;
using vHCS.SYS.Entities;
using Core.Logging;


public partial class Controls_TopHeader : Core.NTier.UserInterface.BaseUserControl
{
    #region CONST
    private const string _PG_AFTER_LOGOUT = "~/Default.aspx";
    #endregion
    protected void Page_Load(object sender, EventArgs e)
    {
        this.BuildTopMenu();
        this.cboGlobalTheme.SelectedValue = SessionManager.Theme;
        this.imgTopBanner.ImageUrl = "~/App_Themes/" + SessionManager.Theme + "/Images/header.jpg";
        this.LoadUserInfo();
        if (!IsPostBack)
        {
            this.AddFavorites();
            
        }
        if (SessionManager.IsEnglish)
        {
            btnChangeToVN.Visible = true;
            btnChangeToEN.Visible = false;
        }
        else
        {
            btnChangeToVN.Visible = false;
            btnChangeToEN.Visible = true;
        }
    }

    protected void Page_Init(object sender, EventArgs e)
    {
        try
        {
           
            cboGlobalTheme.SelectedValue = SessionManager.Theme;
        }
        catch (Exception ex)
        {
            AlertMessage mess = UserInterfaceExceptionHandler.HandleExcetion(ex);
            MessageBox.Show(mess);
        }
    }

        
    /// <summary>
    /// Tạo top menu
    /// </summary>
    protected void BuildTopMenu() {
        try
        {
            ///get current moduleId
            long currModuleId = RequestInfo.ModuleId;
            SessionCacheManager cacher = new SessionCacheManager();
            Collection<ModulesBL> modules = new Collection<ModulesBL>();
            
            //get list of module
            //Tam thoi bo de test loi mat menu
            //CacheKey key = new CacheKey("Telerik.Web.UI", "RadMenu", "BuildTopMenu");
            //if (cacher.Contains(key))            
            //    modules = (Collection<ModulesBL>)cacher.GetData(key);
            //else modules=new ModulesBL().FindDisplayList(SessionManager.Username);

            ////Kiem tra fix loi mat menu
            //if (modules == null)
            //    modules = new ModulesBL().FindDisplayList(SessionManager.Username);
            ////end Kiem tra fix loi mat menu

            if (DataCache.GetCache("BuildTopMenu_" + SessionManager.Username) == null) //Kiểm tra coi có cache này chưa
            {
                modules = new ModulesBL().FindDisplayList(SessionManager.Username);

                if (modules != null)
                {
                    DataCache.SetCache("BuildTopMenu_" + SessionManager.Username, modules);
                }
            }

            try
            {
                modules = (Collection<ModulesBL>)DataCache.GetCache("BuildTopMenu_" + SessionManager.Username);
            }
            catch
            {
                modules = new ModulesBL().FindDisplayList(SessionManager.Username);
            }

            RadMenuOne.Items.Clear();
            //add items to top menu
            foreach (ModulesBL m in modules)
            {
                string moduleName = m.NameEN;
                if (SessionManager.IsVietnammese) moduleName = m.NameVN;

                RadMenuItem item = new RadMenuItem(moduleName);              
                item.Value = m.ModuleId.ToString();
                item.NavigateUrl = "~" + m.DefaultPath;
                if (m.ModuleId == currModuleId) item.Selected = true;               

                RadMenuOne.Items.Add(item);
            }
        }
        catch (Exception ex)
        {
            AlertMessage mess = UserInterfaceExceptionHandler.HandleExcetion(ex);
            MessageBox.Show(mess);
        }
        
        
    }

    /// <summary>
    /// Signout
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btnLogout_Click(object sender, EventArgs e)
    {
        try
        {
            SessionCacheManager cacher = new SessionCacheManager();
            cacher.ClearPerUser();

            //Remove cache
            DataCache.RemoveCache("UserSetting_" + SessionManager.Username);
            DataCache.RemoveCache("FindByUserId" + SessionManager.Username);
            DataCache.RemoveCache("BuildTopMenu_" + SessionManager.Username);
            DataCache.RemoveCache("LoadFavorites_" + SessionManager.Username);
            DataCache.RemoveCache("LoadMenuBar_1" + SessionManager.Username);
            DataCache.RemoveCache("LoadMenuBar_2" + SessionManager.Username);
            DataCache.RemoveCache("LoadMenuBar_3" + SessionManager.Username);
            DataCache.RemoveCache("LoadMenuBar_6" + SessionManager.Username);
            DataCache.RemoveCache("LoadMenuBar_8" + SessionManager.Username);
            DataCache.RemoveCache("LoadMenuBar_9" + SessionManager.Username);
            DataCache.RemoveCache("LoadMenuBar_10" + SessionManager.Username);
            DataCache.RemoveCache("LoadMenuBar_11" + SessionManager.Username);
            DataCache.RemoveCache("LoadMenuBar_12" + SessionManager.Username);

            DataCache.RemoveCache("LoadMenuBarDelegate_1" + SessionManager.UserDelegate);
            DataCache.RemoveCache("LoadMenuBarDelegate_2" + SessionManager.UserDelegate);
            DataCache.RemoveCache("LoadMenuBarDelegate_3" + SessionManager.UserDelegate);
            DataCache.RemoveCache("LoadMenuBarDelegate_6" + SessionManager.UserDelegate);
            DataCache.RemoveCache("LoadMenuBarDelegate_8" + SessionManager.UserDelegate);
            DataCache.RemoveCache("LoadMenuBarDelegate_9" + SessionManager.UserDelegate);
            DataCache.RemoveCache("LoadMenuBarDelegate_10" + SessionManager.UserDelegate);
            DataCache.RemoveCache("LoadMenuBarDelegate_11" + SessionManager.UserDelegate);
            DataCache.RemoveCache("LoadMenuBarDelegate_12" + SessionManager.UserDelegate);
            
            

            //Ghi log đăng thoát thành công
            UserLogging logger = new UserLogging();
            logger.LogOutLogging(SessionManager.Username);

            FormsAuthentication.SignOut();
            Session.Abandon();
            Response.Redirect(_PG_AFTER_LOGOUT);
            Session.RemoveAll();
        }
        catch { }
    }

    /// <summary>
    /// Su kien khi trang duoc khoi tao
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
   

    protected void cboGlobalTheme_SelectedIndexChanged(object sender, RadComboBoxSelectedIndexChangedEventArgs e)
    {
        try
        {
            SessionManager.Theme = cboGlobalTheme.SelectedValue;
            Response.Redirect(Request.Url.AbsoluteUri);
        } 
        catch (Exception ex)
        {
            AlertMessage mess = UserInterfaceExceptionHandler.HandleExcetion(ex);
            MessageBox.Show(mess);
        }
    }

    protected void LoadUserInfo()
    {
        try
        {
            this.lblUsername_V.Text = string.Format("[{0}]", Core.Common.Session.CurrentUser.Username);
            this.lblEmpName_V.Text = string.Empty;
            this.lblUserGroup_V.Text = string.Empty;

            HR_vEmployeeCollection controller = new HR_vEmployeeCollection();
            HR_vEmployeeBL empBO = controller.FindByUsername(Core.Common.Session.CurrentUser.Username);
            SYS_UserGroupCollection controllerG = new SYS_UserGroupCollection();
            SYS_UserGroupBL ugBO = controllerG.FindByUserId(Core.Common.Session.CurrentUser.Username);
            if (empBO != null && empBO.DTO != null)
            {
                string strEmpName = (SessionManager.IsEnglish) ? empBO.DisplayNameEN : empBO.DisplayNameVN;
                this.lblEmpName_V.Text = string.Format("[{0}]", strEmpName);
            }
            if (ugBO != null && ugBO.DTO != null)
            {
                string strGroupName = (SessionManager.IsEnglish) ? ugBO.NameEN : ugBO.NameVN;
                this.lblUserGroup_V.Text = string.Format("[{0}]", strGroupName);
            }
        }
        catch (Exception ex)
        {
            AlertMessage mess = UserInterfaceExceptionHandler.HandleExcetion(ex);
            MessageBox.Show(mess);
        }
    }

    protected void AddFavorites() {
        try
        {
            long lFuncId = Core.Security.CoreMembership.RequestInfo.MasterFunctionId;
            long lModuleId = Core.Security.CoreMembership.RequestInfo.ModuleId;

            this.btnAddFavorites.OnClientClick = string.Format("OpenPopupAddFavorite('{0}','{1}'); return false;", lFuncId,lModuleId);
        } 
        catch (Exception ex)
        {
            AlertMessage mess = UserInterfaceExceptionHandler.HandleExcetion(ex);
            MessageBox.Show(mess);
        }
    }

    protected void btnChangeToEN_Click(object sender, System.Web.UI.ImageClickEventArgs e)
    {
        this.ChangeLanguage("en-US", CoreConfigManager.ENLanguageId);
    }

    protected void btnChangeToVN_Click(object sender, System.Web.UI.ImageClickEventArgs e)
    {       
        this.ChangeLanguage("vi-VN", CoreConfigManager.VNLanguageId);
    }

    protected void ChangeLanguage(string culture,string languageId) {
        try
        {
            //Xóa Cache vì một số dữ liệu phu thuộc vào ngôn ngữ
            SessionCacheManager cacher = new SessionCacheManager();
            cacher.ClearPerUser();
            ApplicationCacheManager appCacher = new ApplicationCacheManager();
            appCacher.Clear();

            SessionManager.LanguageID =languageId;
            SessionManager.CultureInfo = culture;
        }
        catch (Exception ex)
        {
            AlertMessage mess = UserInterfaceExceptionHandler.HandleExcetion(ex);
            MessageBox.Show(mess);
        }
        Response.Redirect(Request.Url.AbsoluteUri);
    }
    /// <summary>
    /// Link của phân hệ
    /// </summary>
    public string ModuleDefaultPath
    {
        get {
            try
            {
                string strLink = string.Empty;
                foreach (RadMenuItem item in RadMenuOne.Items)
                    if (item.Selected)
                        strLink = string.Format(" » <a href='{0}'>{1}</a>", item.NavigateUrl.Replace("~/", "../"), item.Text);
                return strLink;
            }
            catch (Exception ex)
            {
                AlertMessage mess = UserInterfaceExceptionHandler.HandleExcetion(ex);
                MessageBox.Show(mess);
            }
            return string.Empty;
        }
    }
    protected void btnSaveSetting_Click(object sender, EventArgs e)
    {
        try
        {
            
            //MessageBox.ShowByMessCode("10001", MessageType.Successful);
        }
        catch (Exception ex)
        {
            AlertMessage mess = UserInterfaceExceptionHandler.HandleExcetion(ex);
            MessageBox.Show(mess);
        }
    }
}